//
//  WelcomeVM.swift
//  ShouChong
//
//  Created by 陈友文 on 2024/7/15.
//

import Foundation
import SwiftUI

class WelcomeVM:ObservableObject {
    typealias SuccessBlock = (_ res:Any) -> Void
    typealias FailBlock = ((Any?, String) -> Void)
    
    
    func firstRegist(sendData:[String:String],successBlock:@escaping SuccessBlock,failBlock:@escaping FailBlock) {
        YWNetworkTool.share().requestJson(url: "user/firstRegist",parameters: sendData,tips: "加载中...") { res in
            guard let results = res as? [String:Any],
                  let token = results["token"] as? String else {
                YWToast.show(text: "发生错误,请稍等")
                return
            }
            successBlock(token)
        } responseFailBlock: { error, code in
            failBlock(error,code)
        }
    }
    
    func login(account:String,password:String,completion:@escaping (_ token:String)->Void) {
        let sendData = [
            "account":account,
            "password":password
        ]
        YWNetworkTool.share().requestJson(url: "user/login", parameters: sendData) { res in
            DPrint(res)
            guard let results = res as? [String:Any],
                  let status = results["status"] as? Int,
                  let message = results["message"] as? String
            else{
                YWToast.show(text: "登录失败,请稍后再试")
                return
            }
            if status == 200 {
                if let token = results["token"] as? String {
                    YWToast.show(text: "登录成功")
                    completion(token)
                } else {
                    YWToast.show(text: "登录失败,请稍后再试")
                }
            }else {
                YWToast.show(text: message)
            }
        } responseFailBlock: { error, code in
            YWToast.show(text: "登录失败,请稍后再试")
        }
    }
    

}
